<template>
  <van-uploader :after-read="afterRead" :max-count="maxCount" accept="image/*">
    <slot></slot>
  </van-uploader>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { showToast } from "vant";
import { http } from "@/utils/http";

import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineProps({
  multiple: {
    type: Boolean,
    default: false
  },
  maxCount: {
    type: Number,
    default: 1
  }
});

const state = ref(false);

const emit = defineEmits(["onSuccess"]);

const afterRead = (file:any) => {
  state.value = false;
  if (file && file.length > 1) {
    file.forEach((item:any) => {
      if (item.status === "failed") {
        showToast('网络异常，请重试');
        state.value = true;
      }
      if (item.file.size >= 10400 * 1024) {
        state.value = true;
        showToast('文件大小不能超过 10M');
        return;
      }
    });
    if (!state.value) {
      file.forEach((item:any) => {
        submit(item.file);
      });
    }
  } else {
    if (file.status === "failed") {
      showToast('网络异常，请重试');
    }
    if (file.file.size >= 10400 * 1024) {
      showToast('文件大小不能超过 10M');
      return;
    }
    submit(file.file);
  }
  // if (file.status === 'failed') {
  //   showToast('网络异常，请重试');
  // }
  // if (file.file.size >= 5200 * 1024) {
  //   showToast('文件大小不能超过 5M');
  //   return;
  // }
  // submit(file.file);
};

const submit = (file: any) => {
  const formData = new FormData();
  formData.append("name", file.name);
  formData.append("file", file);
  console.log(formData)
  http
    .request({
      url: "/upload",
      method: "post",
      data:formData,
      headers: {
        'Content-Type': 'multipart/form-data;charset=UTF-8'
      },
    })
    .then((data:any) => {
      emit("onSuccess", data.data.url);
    })
    .catch(err => {
      showToast('上传失败了');
      console.log(err);
    });
};
</script>

<style lang="less" scoped>
.custom-image .van-empty__image {
  //width: px2rem(180);
  //height: px2rem(180);
}
</style>
